<?php
/**
 * Created by PhpStorm.
 * User: 王溪
 * Date: 2020/8/24
 * Time: 20:01
 */

namespace app\index\controller;


class Wood extends Base
{
    private $ApiKey = 'XB40tIAtXZWUd1Bw5dzgdhd9';
    private $SecretKey = 'FNmRfi8aKgHKe72xkQhdZQ6kH7ezG249';

    /**
     * @name 展示
     * @return mixed
     * @author wx
     * @date 2020/8/26 15:07
     */
    public function index()
    {
        $open_id = 'qwer';

        $this->assign('open_id', $open_id);

        return $this->fetch('index');
    }

    /**
     * @name 提交
     * @author wx
     * @date 2020/8/26 9:59
     */
    public function commit()
    {
        $open_id = input('open_id');
        $params = input('params/a');

        $data = json_decode($params[0], true);


        $insertData = $unit_total_price = array();

        $total_price = 0;
        foreach ($data as $k => $arrV){

            $tmp['open_id'] = $open_id;
            $tmp['long'] = empty($arrV['long']) ? 0 : $arrV['long'];
            $tmp['width'] = empty($arrV['width']) ? 0 : $arrV['width'];
            $tmp['height'] = empty($arrV['height']) ? 0 : $arrV['height'];
            $tmp['density'] = empty($arrV['density']) ? 1.1 : $arrV['density'];
            $tmp['unit_price'] = empty($arrV['unit_price']) ? 1400 : $arrV['unit_price'];
            $tmp['total_price'] = $this->compute($tmp);
            $tmp['image'] = empty($arrV['image']) ? '' : $arrV['image'];

            $unit_total_price[$k] = $tmp['total_price'];
            $total_price += $tmp['total_price'];

            $insertData[$k] = $tmp;
        }


        if(!empty($insertData)){
            db('wood')->insertAll($insertData);
        }

        $return['code'] = 200;
        $return['msg'] = 'success';
        $return['total_price'] = $total_price;
        $return['unit_total_price'] = $unit_total_price;

        echo json_encode($return);die;
    }

    /**
     * 计算
     * @param $data
     */
    private function compute($data)
    {
        $total = $data['long'] * $data['width'] * $data['height'] * $data['density'] * $data['unit_price'];

        $total = round($total, 2);

        return $total;
    }

    /**
     * @name 图片上传
     * @author wx
     * @date 2020/8/26 16:31
     */
    public function upload()
    {

        $files = $this->request->file('img');


        if(empty($files)){
            echo json_encode(['code' => 201, 'msg' => 'no file upload']);die;
        }

        $dirPath = 'uploads';
        $info = $files->move($dirPath);

        $path = $info->getSaveName();

        $filePath = $dirPath .'/'. $path;



        //获取token
        $tokenArr = $this->getBaiduToken();

        if(isset($tokenArr)){
            $token = $tokenArr['access_token'];

        }else{
            echo json_encode(['code' => 202, 'msg' => $tokenArr['error_description']]);die;
        }



        //获取手写文字
        $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting?access_token=' . $token;

        $filePath = $filePath;

        $img = file_get_contents($filePath);
        $img = base64_encode($img);

        $params = array(
            'image' => $img
        );

        $res = $this->weChatCurl($url, 1, $params);

        //处理文字
        $str = isset($res['words_result'][0]['words']) ? $res['words_result'][0]['words'] : '';

        preg_match_all('/\d+/', $str, $pregArr);

        $long = isset($pregArr[0][0]) ? $pregArr[0][0] : 0;
        $width = isset($pregArr[0][1]) ? $pregArr[0][1] : 0;
        $height = isset($pregArr[0][2]) ? $pregArr[0][2] : 0;

        //返回数据
        $returnData['file_path'] = $filePath;
        $returnData['long'] = $long;
        $returnData['width'] = $width;
        $returnData['height'] = $height;

        echo json_encode(['code' => 200, 'msg' => 'success', 'data' => $returnData]);die;
    }

    /**
     * @name 获取百度token
     * @author wx
     * @date 2020/8/25 10:22
     */
    public function getBaiduToken()
    {
        $url = 'https://aip.baidubce.com/oauth/2.0/token?';


        $post_data['grant_type']       = 'client_credentials';
        $post_data['client_id']      = $this->ApiKey;
        $post_data['client_secret'] = $this->SecretKey;
        $o = "";

        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);


        $responseData = $this->weChatCurl($url, 1, $post_data);

        return $responseData;
    }



    function weChatCurl($url, $type=0, $data = ''){
        //dump($url);die;
        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);// CURLOPT_URL 指定请求的URL
        //此选项确定curl是否验证对等体的证书的真实性。值1表示卷曲验证; 0（零）表示没有。
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        //检查证书中的主机名对于您要连接的主机名有效，将独立于CURLOPT_SSL_VERIFYPEER选项完成。
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //CURLOPT_RETURNTRANSFER 设置为1表示稍后执行的curl_exec函数的返回是URL的返回字符串，而不是把返回字符串定向到标准输出并返回TRUE；
// CURLOPT_POST : 如果你想PHP去做一个正规的HTTP POST，设置这个选项为一个非零值。这个POST是普通的 application/x-www-from-urlencoded 类型，多数被HTML表单使用。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        if($type) {
            curl_setopt($ch, CURLOPT_POST, 1);
            //CURLOPT_POSTFIELDS : 传递一个作为HTTP “POST”操作的所有数据的字符串。
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        // 3. 执行并获取内容
        $output = curl_exec($ch);
        // 4. 释放curl句柄
        curl_close($ch);

        $jsoninfo = json_decode($output, true);
        return $jsoninfo;
    }

}